package com.yazi.mxz.gather.common;

import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.resizers.configurations.ScalingMode;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.PageRequest;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.myframework.smhj.common.tool.CommonUtil;
import com.yazi.mxz.gather.entity.http.LiantuResBody;
import com.yazi.mxz.gather.entity.http.OcrkingResBody;
import com.yazi.mxz.gather.entity.repository.LiantuLog;
import com.yazi.mxz.gather.entity.repository.Product;
import com.yazi.mxz.gather.entity.repository.SettingLog;
import com.yazi.mxz.gather.main.RegionUpdate;
import com.yazi.mxz.gather.main.goods.JqbhNet;
import com.yazi.mxz.gather.main.goods.StoreGoodsUpdate;
import com.yazi.mxz.gather.main.goods.StoreGoodsUpload;
import com.yazi.mxz.gather.main.store.ChachabaCom;
import com.yazi.mxz.gather.main.store.StoreUpdate;
import com.yazi.mxz.gather.main.store.StoreUpload;
import com.yazi.mxz.gather.repository.LiantuLogRepository;
import com.yazi.mxz.gather.repository.ProductRepository;
import com.yazi.mxz.gather.repository.SettingLogRepository;

/**
 * Hello world!
 * 
 */
public class App {
	public static ApplicationContext context;
	
	//static final String ACCESS_DB_URL = "jdbc:odbc:goodsbarcode";
	//static final String ACCESS_DB_URL = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:/项目/mo_yq5/barcode/GoodsBarcode.mdb";
	static final String ACCESS_DB_URL = "jdbc:Access:///E:/项目/mo_yq5/barcode/GoodsBarcode.mdb";
	static SettingLogRepository settingLogRepository;
	static ObjectMapper om;
	static XmlMapper xm;
	static {
		
		context = new ClassPathXmlApplicationContext("spring.xml");
		settingLogRepository = context.getBean(SettingLogRepository.class);
		
		om = new ObjectMapper();
		om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		xm = new XmlMapper();
		xm.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		
	}

	public static void main(String[] args) {
		System.out.println("Hello World!601650");
		ProductRepository productRepository = context.getBean(ProductRepository.class);
		System.out.println(productRepository.count());
		/*
		SettingLog log = settingLogRepository.findOne(SettingLog.ID);
		log.setPicNum(10240);
		settingLogRepository.save(log);
		*/
		//activateJob();
		//App app = new App();
		
		// 商品相关
		//new GdcmtzCom().start();
		//new BsbqsCom().start();
		//new DuolimiCn().start();
		//new LifufoodCom().start();// 1, 150
		//new JgmallCn().start();// 1, 118
		//new ZgpfptCom().start();
		//new YjgxcsCom().start();// 1,678
		//new Ssls8Com().start();// 1,243
		//new Ydd668Com().start();// 1,288
		//new JqbhNet().start();// 1, 390
		
		// 店铺相关
		//new ChachabaCom().start();// 1,37
		//new StoreUpload().start();
		//new StoreUpdate().start();
		//System.out.println(String.format("%.1f0", 9.83742));
		//new StoreGoodsUpload().start();
		//new StoreGoodsUpdate().start();
		
		//new RegionUpdate().start();
		//app.spring();
		//app.startLoadBarcodeInfo(null, null);
		//access();
		//System.out.println(getBarCode("692345065763"));
		
		/*
		SettingLog log = settingLogRepository.findOne(SettingLog.ID);
		log.setPicNum(0);
		settingLogRepository.save(log);
		
		int pageNum = -1;
		List<Product> list;
		String pic;
		String srcPic;
		while(true) {
			
			pageNum++;
			list = productRepository.findByPicIsNotNull(new PageRequest(pageNum, 1000));
			if (list.size() == 0) {
				break;
			}
			
			for (Product pro : list) {
				srcPic = "http://localhost/res/test/picture/" + pro.getPic();
				pic = saveGoodsImageV1(srcPic);
				pro.setPic(pic);System.out.println("小图:" + pic);
				pic = saveGoodsMiddleImageV1(srcPic);
				pro.setMidPic(pic);System.out.println("中图:" + pic);
				pic = saveGoodsBigImageV1(srcPic);
				pro.setBigPic(pic);System.out.println("大图:" + pic);
				
				if (null == pro.getMidPic()) {
					srcPic = "http://localhost/res/test/picture/" + pro.getBigPic();
					pic = saveGoodsMiddleImageV1(srcPic);
					pro.setMidPic(pic);System.out.println("中图:" + pic);
					pic = saveGoodsBigImageV1(srcPic);
					pro.setBigPic(pic);System.out.println("大图:" + pic);
				} else if (null == pro.getBigPic()) {
					srcPic = "http://localhost/res/test/picture/" + pro.getBigPic();
					pic = saveGoodsBigImageV1(srcPic);
					pro.setBigPic(pic);System.out.println("大图:" + pic);
				}
				productRepository.save(pro);
			}
			
		}
		*/
	}
	
	private void spring() {
		
		
		LiantuLogRepository liantuLogRepository = context.getBean(LiantuLogRepository.class);
		
		final String[] codes = {
			"690000000608", 
			"690100000000",
			"690200000000",
			"690300000000",
			"690400000000",
			"690500000000",
			"690600000000",
			"690700000000",
			"690800000000",
			"690900000000",
			"691100000000",
			"691200000000",
			"691300000000",
			"691400000000",
			"691500000000",
			"691600000000",
			"691700000000",
			"691800000000",
			"691900000000",
			"692000000000", 
			"692100000000",
			"692200000000",
			"692300000000",
			"692400000000",
			"692500000000",
			"692600000000",
			"692700000000",
			"692800000000",
			"692900000000",
			"692000000000", 
			"692100000000",
			"692200000000",
			"692300000000",
			"692400000000",
			"692500000000",
			"692600000000",
			"692700000000",
			"692800000000",
			"692900000000",
			"693000000000", 
			"693100000000",
			"693200000000",
			"693300000000",
			"693400000000",
			"693500000000",
			"693600000000",
			"693700000000",
			"693800000000",
			"693900000000",
			"694000000000", 
			"694100000000",
			"694200000000",
			"694300000000",
			"694400000000",
			"694500000000",
			"694600000000",
			"694700000000",
			"694800000000",
			"694900000000",
			"695000000000", 
			"695100000000",
			"695200000000",
			"695300000000",
			"695400000000",
			"695500000000",
			"695600000000",
			"695700000000",
			"695800000000",
			"695900000000",
			"696000000000", 
			"696100000000",
			"696200000000",
			"696300000000",
			"696400000000",
			"696500000000",
			"696600000000",
			"696700000000",
			"696800000000",
			"696900000000",
			"697000000000", 
			"697100000000",
			"697200000000",
			"697300000000",
			"697400000000",
			"697500000000",
			"697600000000",
			"697700000000",
			"697800000000",
			"697900000000",
			"698000000000", 
			"698100000000",
			"698200000000",
			"698300000000",
			"698400000000",
			"698500000000",
			"698600000000",
			"698700000000",
			"698800000000",
			"698900000000",
			"699000000000", 
			"699100000000",
			"699200000000",
			"699300000000",
			"699400000000",
			"699500000000",
			"699600000000",
			"699700000000",
			"699800000000",
			"699900000000"
		};
		
		LiantuLog log = new LiantuLog();
		for (int i = 0; i< codes.length; i++) {
			log = new LiantuLog();
			log.setSeial(i + 1);
			log.setCurrent(codes[i]);
			log.setEnd("" + (Long.parseLong(codes[i]) + 999999));
			log.setStart(codes[i]);
			liantuLogRepository.insert(log);
		}
		
	}
	
	private void startLoadBarcodeInfo(String code, Integer type) {
		LiantuLogRepository liantuLogRepository = context.getBean(LiantuLogRepository.class);
		
		if (null == code) {
			
			List<LiantuLog> list = liantuLogRepository.findAll();
			for (final LiantuLog log : list) {
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						startLoadBarcodeInfo(log.getCurrent(), log.getSeial());
					}
					
				}).start();
			}
			return;
			
		}
		
		LiantuLog log = liantuLogRepository.findOne(type);
		log.setCurrent(code);
		
		String barcode = getBarCode(code);
		System.out.println(type + ": " + barcode);
		
		barcodeInfo(barcode);
		
		Long next = Long.parseLong(code) + 1;
		if (next < Long.parseLong(log.getEnd())) {
			startLoadBarcodeInfo("" + next, type);
		}
		
	}

	private void access() {
		try {
			
			//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			Class.forName("com.hxtt.sql.access.AccessDriver").newInstance();
			
			Connection con = DriverManager.getConnection(ACCESS_DB_URL, "", "");

			Statement stmt = con.createStatement();
			stmt.setFetchSize(10);
			
			accessInsertMongodb(stmt, 500);

		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}

	}

	private void accessInsertMongodb(Statement stmt, int page) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		int start = page * 1000;
		int end = start + 1001;
		String sql = "select * from GoodsBarcode where val(id) > " + start + " and val(id) < " + end + " order by val(id)";

		
		ResultSet rs = stmt.executeQuery(sql);
		
		ResultSetMetaData resultSetMetaData = rs.getMetaData();
		int iNumCols = resultSetMetaData.getColumnCount();
		for (int i = 1; i <= iNumCols; i++) {
			System.out.println(resultSetMetaData.getColumnLabel(i) + "  "
					+ resultSetMetaData.getColumnTypeName(i));
		}

		Object colval;
		Product product = new Product();
		ProductRepository productRepository = context.getBean(ProductRepository.class);
		boolean hasResult = false;
		
		while (rs.next()) {
			
			if (rs.isFirst()) {
				hasResult = true;
			}
			System.out.println("row："+ rs.getRow());
			product.setArea(rs.getString("location"));
			product.setBarcode(rs.getString("barcode"));
			product.setName(rs.getString("name"));
			product.setSpec(rs.getString("spec"));
			product.setSpell(rs.getString("pinyin"));
			product.setUnit(rs.getString("unit"));
			
			if (!productRepository.exists(product.getBarcode())) {
				productRepository.insert(product);
			} else {
				System.out.println(rs.getString("id") +"："+ product.getBarcode() + " is exists");
			}
			
			for (int i = 1; i <= iNumCols; i++) {
				colval = rs.getObject(i);
				System.out.print(colval + "  ");
			}
			System.out.println();
		}
		System.out.println("total：" + productRepository.count());
		System.out.println("page：" + page);
		rs.close();
		
		if (hasResult) {
			accessInsertMongodb(stmt, page + 1);
		}
		
	}

	private void barcodeInfo(String barcode) {

		CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();

		try {
			httpclient.start();
			final HttpPost req = new HttpPost("http://www.liantu.com/tiaoma/query.php");
			req.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("ean", barcode));
			req.setEntity(new UrlEncodedFormEntity(nvps));
			Future<HttpResponse> future = httpclient.execute(req, null);
			
			HttpResponse res = future.get();
			String body = EntityUtils.toString(res.getEntity());
			
			System.out.println(req.getRequestLine() + "->" + res.getStatusLine());
			System.out.println(body);
			
			if (body.equals("false")) {
				return;
			}
			
			LiantuResBody lianTu= om.readValue(body, LiantuResBody.class);
			
			ProductRepository productRepository = context.getBean(ProductRepository.class);
			
			
			if (!productRepository.exists(lianTu.getBarCode())) {
				//lianTu.getBarCode();
				//lianTu.getCountry();
				//lianTu.getFacCode();
				//lianTu.getFacName();
				//lianTu.getName();
				/*lianTu.getNameSrc();*/
				//lianTu.getPrice();
				//lianTu.getSupplier();
				
				// "暂无"
				if (null == lianTu.getNameSrc() || lianTu.getNameSrc().equals("http://www.liantu.com/tiaoma/eantitle.php?title=dUd3Z3BhS2J3cUk9")) {
					System.out.println(barcode + ":暂无");
					return;
				}

				saveImage(lianTu.getNameSrc(), barcode);
				
				/*
				String name = lianTu.getName();
				if (null == name || name.isEmpty()) {
					name = barcode(lianTu.getNameSrc(), lianTu.getBarCode());
				}
				if (null == name || name.equals("暂无")) {
					return;
				}
				*/
				
				Product product = new Product();
				product.setIsCheckName(false);
				product.setArea(lianTu.getCountry());
				product.setBarcode(lianTu.getBarCode());
				product.setName("未处理");
				//product.setSpec(rs.getString("spec"));
				//product.setSpell(rs.getString("pinyin"));
				//product.setUnit(rs.getString("unit"));
				product.setPrice(lianTu.getPrice());
				product.setSupplier(lianTu.getSupplier());
				product.setFacCode(lianTu.getFacCode());
				product.setFacName(lianTu.getFacName());
				productRepository.insert(product);
				
			} else {
				
				Product product = productRepository.findOne(lianTu.getBarCode());
				if (null != lianTu.getCountry() && null == product.getArea()) {
					product.setArea(lianTu.getCountry());
				}
				if (null != lianTu.getName() && null == product.getName()) {
					product.setName(lianTu.getName());
				}
				if (null != lianTu.getPrice() && null == product.getPrice()) {
					product.setPrice(lianTu.getPrice());
				}
				if (null != lianTu.getSupplier() && null == product.getSupplier()) {
					product.setSupplier(lianTu.getSupplier());
				}
				if (null != lianTu.getFacCode() && null == product.getFacCode()) {
					product.setFacCode(lianTu.getFacCode());
				}
				if (null != lianTu.getFacName() && null == product.getFacName()) {
					product.setFacName(lianTu.getFacName());
				}
				
				productRepository.save(product);
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private String barcode(final String nameSrc, final String barcode) {
		// "暂无"
		if (nameSrc.equals("http://www.liantu.com/tiaoma/eantitle.php?title=dUd3Z3BhS2J3cUk9")) {
			System.out.println(barcode + ":暂无");
			return null;
		}
		// the url below can not be changed !!
		final String apiUrl = "http://lab.ocrking.com/ok.html";
		// replace the word KEY below with your apiKey obtained by Email
		final String apiKey = "b730ad71600e9941a89pAWLCqhZKriuds0Zb0FUN1jKWo2gany2WcuuwGoBbL4w8ATLHDO4w";

		Map<String, String> dataMap = new HashMap<String, String>();
		Map<String, String> fileMap = new HashMap<String, String>();
		
		try {
			
			if (checkImageSize(nameSrc)) {
				dataMap.put("url", nameSrc);
			} else {
				fileMap.put("ocrfile", resizeImage(nameSrc, barcode));
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		}
		
		dataMap.put("service", "OcrKingForCaptcha");
		dataMap.put("language", "sim");
		dataMap.put("type", nameSrc);

		dataMap.put("apiKey", apiKey);
		
		String ret = postMultipart(apiUrl, dataMap, fileMap);
		System.out.println(ret);
		OcrkingResBody ocrking = null;
		try {
			ocrking = xm.readValue(ret, OcrkingResBody.class);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		if (null == ocrking) {
			return null;
		} 
		String name = ocrking.getResultList().getItem().getResult();
		if (null == name || name.isEmpty()) {
			System.out.println(barcode + ":[空]");
			return null;
		}
		if (ocrking.getResultList().getItem().getStatus().equals("true")) {
			System.out.println(barcode + ":" + name);
			return name;
		}
		return null;
		
	}

	/**
	 * post data with file uploading
	 * 
	 * @param urlStr
	 *            the address to upload
	 * @param dataMap
	 *            post data
	 * @param fileMap
	 *            file to upload
	 * @return xml result
	 */
	private String postMultipart(String urlStr, Map<String, String> dataMap,
			Map<String, String> fileMap) {
		String res = "";
		HttpURLConnection conn = null;
		String boundary = "----------------------------OcrKing_Client_Aven_s_Lab";
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Referer", "http://lab.ocrking.com/?javaclient0.1)");
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// data
			if (dataMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator<Map.Entry<String, String>> iter = dataMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<String, String> entry = iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName
							+ "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// file
			if (fileMap != null) {
				Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<String, String> entry = iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					File file = new File(inputValue);
					String filename = file.getName();

					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName
							+ "\"; filename=\"" + filename + "\"\r\n");
					strBuf.append("Content-Type:application/octet-stream\r\n\r\n");

					out.write(strBuf.toString().getBytes());

					DataInputStream in = new DataInputStream(new FileInputStream(file));
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}
			}

			byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// handle the response
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			System.out.println("error " + urlStr);
			// e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
	}

	private String resizeImage(String titleUrl, String barCode) throws IOException {
		String destFile = "E:\\项目\\mo_yq5\\barcode\\barcodeimg\\" + barCode + ".jpg";
		Thumbnails.of(new URL(titleUrl)).scale(1).toFile(destFile);
		/*
		BufferedImage bi = Thumbnails.of(new URL(titleUrl)).scale(1).asBufferedImage();
		int width = bi.getWidth();
		int height = bi.getHeight();
		if (width > 300) {
			width = 250;
		}
		if (height > 150) {
			height = 150;
		}
		Thumbnails.of(new URL(titleUrl)).size(width, height).crop(Positions.CENTER_LEFT).toFile(destFile);
		*/
		return destFile;
	}
	
	private void saveImage(String titleUrl, String barCode) throws IOException {
		String destFile = "E:\\项目\\mo_yq5\\barcode\\barcodeimg\\" + barCode + ".jpg";
		Thumbnails.of(new URL(titleUrl)).scale(1).toFile(destFile);
	}

	private boolean checkImageSize(String titleUrl) throws IOException {
		BufferedImage bi = Thumbnails.of(new URL(titleUrl)).scale(1).asBufferedImage();
		if (bi.getWidth() < 300 || bi.getHeight() < 150) {
			return false;
		}
		return true;
	}
	
	/**
	 * 计算出条码的校验码
	 * @param barCode
	 * @return
	 */
	private String getBarCode(String code) {
		char[] c = code.toCharArray();
		int check = 0;
		int odd = 0;
		int even = 0;
		for (int i = c.length - 1; i >= 0; i -= 2) {
			odd += Integer.parseInt("" + c[i]);
		}
		for (int i = c.length - 2; i >= 0; i -= 2) {
			even += Integer.parseInt("" + c[i]);
		}
		check = odd * 3 + even;
		return code + (check / 10 * 10 + (check % 10 == 0 ? 0 : 10) - check);
	}
	

	public static String saveGoodsImage(String imgUrl, String barCode) {
		String name = CommonUtil.randomLN(12) + barCode + ".jpg";
		String destFile = "E:\\项目\\mo_yq5\\barcode\\goodsimg\\" + name;
		try {
			Thumbnails.of(new URL(imgUrl)).scale(1).toFile(destFile);
		} catch (Exception e) {
			System.out.println("图片保存失败: " + imgUrl);
			name = null;
		}
		return name;
	}
	
	public static String saveGoodsBigImage(String imgUrl, String name) {
		String destFile = "E:\\项目\\mo_yq5\\barcode\\goodsimgbig\\" + name;
		try {
			Thumbnails.of(new URL(imgUrl)).scale(1).toFile(destFile);
		} catch (Exception e) {
			System.out.println("图片保存失败: " + imgUrl);
			name = null;
		}
		return name;
	}
	
	public static String saveGoodsImageV1(String imgUrl) {
		return saveGoodsImageV1(imgUrl, null);
	}
	public static String saveGoodsBigImageV1(String imgUrl) {
		return saveGoodsImageV1(imgUrl, "b");
	}
	public static String saveGoodsMiddleImageV1(String imgUrl) {
		return saveGoodsImageV1(imgUrl, "m");
	}
	
	private static String saveGoodsImageV1(String imgUrl, String type) {
		if (null == imgUrl) {
			return null;
		}
		if (null == type) {
			type = "s";
		}
		
		SettingLog log;
		String path, dest;
		File file;
		BufferedImage bi;
		int width, height;
		
		if (type.equals("s")) {
			width = 150; height = 113;			
		} else if (type.equals("m")) {
			width = 400; height = 300;	
		} else if (type.equals("b")) {
			width = 800; height = 600;
		} else {
			width = 1000; height = 1000;
		}
		
		try {
			
			log = settingLogRepository.findOne(SettingLog.ID);
			if (null == log) {
				log = new SettingLog();
				log.setId(SettingLog.ID);
				log.setPicNum(0);
				settingLogRepository.insert(log);
			}
			if (type.equals("s")) {
				log.setPicNum(log.getPicNum() + 1);
				System.out.println("pic num: " + log.getPicNum());
				settingLogRepository.save(log);
			}
			
			path = getDirPath(log.getPicNum()) + type + "\\" +  CommonUtil.randomLN(8) + ".jpg";
			dest = "F:\\项目\\mo_yq5\\barcode\\picture\\" + path;
			file = new File(dest);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			
			bi = Thumbnails.of(new URL(imgUrl)).scale(1).asBufferedImage();
			// 小图
			if (bi.getWidth() <= width && bi.getHeight() <= height) {
				Thumbnails.of(new URL(imgUrl)).scale(1).toFile(dest);
			} else {
				Thumbnails.of(new URL(imgUrl)).size(width, height).toFile(dest);
				/*
				bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				bi.getGraphics().setColor(Color.WHITE);
				bi.getGraphics().fillRect(0, 0, bi.getWidth(), bi.getHeight());
				Thumbnails.of(bi).watermark(Positions.CENTER, Thumbnails.of(new URL(imgUrl)).size(bi.getWidth(), bi.getHeight()).asBufferedImage(), 1).scale(1).toFile(dest);
				*/
			}
			
			
			path = path.replaceAll("\\\\", "/");
			
		} catch (Exception e) {
			System.out.println("图片保存失败: " + imgUrl);
			path = null;
		}
		
		return path;
		
	}
	
	public static void setPic(String picUrl, PicObject picObj) {
		BufferedImage bi = null;
		
		try {
			bi = Thumbnails.of(new URL(picUrl)).scale(1).asBufferedImage();
		} catch (Exception e) {
			System.out.println("图片路径有误:" + picUrl);
		}
		if (null == bi) {
			return;
		}
		
		if (null == picObj.getPic()) {
			picObj.setPic(picUrl);
		}
		if (null == picObj.getMidPic() && (bi.getWidth() >= 400 && bi.getHeight() >= 300)) {
			picObj.setMidPic(picUrl);
		}
		if (null == picObj.getBigPic() && (bi.getWidth() >= 800 && bi.getHeight() >= 600)) {
			picObj.setBigPic(picUrl);
		}
		return;
	}
	
	public static void delGoodsImageV1(String name) {
		if (null == name) {
			return;
		}
		File file;
		String fileName;
		try {
			fileName = "E:\\项目\\mo_yq5\\barcode\\picture\\" + name;
			file = new File(fileName);
			if (file.exists()) {
				System.out.println("删除图片: " + fileName);
				file.delete();
			}
		} catch (Exception e) {
			System.out.println("图片删除失败: " + name);
		}
	}
	
	public static String delGoodsImage(String name) {
		File file;
		String fileName;
		try {
			fileName = "E:\\项目\\mo_yq5\\barcode\\goodsimg\\" + name;
			file = new File(fileName);
			if (file.exists()) {
				System.out.println("删除图片(小): " + fileName);
				file.delete();
			}
			fileName = "E:\\项目\\mo_yq5\\barcode\\goodsimgbig\\" + name;
			file = new File(fileName);
			if (file.exists()) {
				System.out.println("删除图片(大): " + fileName);
				file.delete();
			}
			
		} catch (Exception e) {
			System.out.println("图片删除失败: " + name);
			name = null;
		}
		return name;
	}
	

	/**
	 * 校验条码是否有效
	 * @param barCode
	 * @return
	 */
	public static boolean checkBarCode(String barCode) {
		char[] c = barCode.toCharArray();
		try {
			// 国际零售商品条码
			return Integer.parseInt("" + c[c.length -1]) == getCheckBarCode(barCode);
		} catch (Exception e) {
			System.out.println("不合格条码:" + barCode);
		}
		return false;
	}
	
	/**
	 * 计算出条码的校验码
	 * @param barCode
	 * @return
	 */
	private static int getCheckBarCode(String barCode) {
		char[] c = barCode.toCharArray();
		int check = 0;
		int odd = 0;
		int even = 0;
		for (int i = c.length - 2; i >= 0; i -= 2) {
			odd += Integer.parseInt("" + c[i]);
		}
		for (int i = c.length - 3; i >= 0; i -= 2) {
			even += Integer.parseInt("" + c[i]);
		}
		check = odd * 3 + even;
		return check / 10 * 10 + (check % 10 == 0 ? 0 : 10) - check;
	}
	
	/**
	 * 根据累计文件数据,计算出目标目录
	 * @param fileNum
	 * @return
	 */
	private static String getDirPath(long sum) {
		
		final long s = sum;// 总文件数
		final int p = 1000;// 每个文件夹目录数
		final int a = 1024;// 每个目录文件数
		// 使用等比数列求和公式计算项数(级别)
		double n = Math.log(1 - (s * (1 - p))/a)/Math.log(p);// 最大级
		int n1 = new Double(n).intValue();// 实际级别
		if (n > n1) {
			n1 += 1;
		}
		long s1;// 最大一级文件数
		if (n1 > 1) {
			s1 = new Double(s - (a * (1 - Math.pow(p, n1 - 1)))/(1-p)).longValue();
		} else {
			s1 = s;
		}
		long num= s1/a + (s1%a > 0 ? 1 : 0);// 最大一级目录数(序号)
		String path = "";
		// 从最底级开始向上逐一级找目录编号
		while(true) {
			//long destNum = num%p; // 当前级目录编号
			path = num%p + File.separator + path;
			num = num/p + (num%p > 0 ? 1 : 0) ; // 上一级目录数(序号)
			if (n1 == 2) {
				break;
			}
			n1--;
		}
		return path;
	}

	public static class PicObject {
		private String pic;
		private String midPic;
		private String bigPic;
		public String getPic() {
			return pic;
		}
		public void setPic(String pic) {
			this.pic = pic;
		}
		public String getMidPic() {
			return midPic;
		}
		public void setMidPic(String midPic) {
			this.midPic = midPic;
		}
		public String getBigPic() {
			return bigPic;
		}
		public void setBigPic(String bigPic) {
			this.bigPic = bigPic;
		}
		
	}
}
